package com.woniuxy.woniuticket.notification.config;



import com.woniuxy.woniuticket.notification.handle.MyWebSocketHandler;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.Map;
//配置WebSocket的config
@Component
//@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig  implements WebSocketConfigurer,WebMvcConfigurer {
    @Resource
    private MyWebSocketHandler handler;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       registry.addViewController("test").setViewName("test");
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(handler, "/wsMy").addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
                        String jspCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("jspCode");
                        if (jspCode != null) {
                            map.put("jspCode", jspCode);
                        } else {
                            return false;
                        }
                        return true;
            }

            @Override
            public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

            }
        });
    }
}

